<template>
  <div class="recognize-container">
    <h1>人脸识别</h1>
    <div class="recognize-form">
      <div class="form-group">
        <label>上传照片进行识别</label>
        <div 
          class="upload-area" 
          :class="{ 'has-image': imagePreview }"
          @click="triggerFileInput"
          @dragover.prevent
          @dragenter.prevent
          @drop.prevent="handleDrop"
        >
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            style="display: none"
            @change="handleFileChange"
          >
          
          <div v-if="!imagePreview" class="upload-placeholder">
            <div class="upload-icon">📸</div>
            <p>点击或拖拽图片到此处上传</p>
            <p class="upload-hint">支持 JPG、PNG 格式</p>
          </div>
          
          <div v-else class="image-preview">
            <img :src="imagePreview" alt="预览图片">
            <button class="change-image-btn" @click.stop="triggerFileInput">
              更换图片
            </button>
          </div>
        </div>
      </div>
      
      <button 
        class="recognize-btn" 
        :disabled="!imagePreview || isLoading"
        @click="handleRecognize"
      >
        {{ isLoading ? '识别中...' : '开始识别' }}
      </button>
      
      <!-- 识别结果 -->
      <div v-if="result" class="result-section" :class="resultClass">
        <div v-if="result.recognized" class="success-result">
          <div class="result-icon success">✅</div>
          <h3>识别成功</h3>
          <p>欢迎您，<strong>{{ result.user.name }}</strong>！</p>
          <p class="user-id">用户ID: {{ result.user.id }}</p>
        </div>
        <div v-else class="error-result">
          <div class="result-icon error">❌</div>
          <h3>未识别到匹配用户</h3>
          <p>{{ result.message || '请确认是否已注册或上传清晰照片' }}</p>
        </div>
      </div>
      
      <!-- 错误消息 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
    
    <div class="tips-section">
      <h3>识别提示</h3>
      <ul>
        <li>确保照片清晰，光线充足</li>
        <li>人脸应与注册时的状态保持一致</li>
        <li>避免面部遮挡和剧烈表情变化</li>
        <li>尽量在相似环境下进行识别</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

const imagePreview = ref('')
const fileInput = ref(null)
const isLoading = ref(false)
const result = ref(null)
const errorMessage = ref('')

// 计算结果样式类
const resultClass = computed(() => {
  if (!result.value) return ''
  return result.value.recognized ? 'success' : 'error'
})

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    processImage(file)
  }
}

// 处理拖拽上传
const handleDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file) {
    processImage(file)
  }
}

// 处理图片
const processImage = (file) => {
  // 验证文件类型
  if (!file.type.match('image.*')) {
    showError('请上传有效的图片文件')
    return
  }
  
  // 读取图片预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
    // 清除之前的结果
    result.value = null
    errorMessage.value = ''
  }
  reader.readAsDataURL(file)
}

// 显示错误消息
const showError = (message) => {
  errorMessage.value = message
  setTimeout(() => {
    errorMessage.value = ''
  }, 3000)
}

// 识别人脸
const handleRecognize = async () => {
  if (!imagePreview.value) {
    showError('请上传照片进行识别')
    return
  }
  
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    // 发送识别请求
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'
    const response = await axios.post(`${apiBaseUrl}/recognize`, {
      image: imagePreview.value
    })
    
    // 处理成功响应
    result.value = {
      recognized: response.data.recognized,
      user: response.data.user,
      message: response.data.message || ''
    }
  } catch (error) {
    console.error('识别请求失败:', error)
    // 特别处理404错误（未识别到用户）
    if (error.response && error.response.status === 404) {
      // 显示未识别状态，而不是错误消息
      result.value = {
        recognized: false,
        message: '未识别'
      }
    } else {
      // 其他错误才显示错误消息
      showError('网络错误，请稍后重试')
    }
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时添加拖拽事件监听
onMounted(() => {
  // 阻止整个页面的拖拽默认行为
  document.addEventListener('dragover', (e) => {
    e.preventDefault()
  })
  document.addEventListener('drop', (e) => {
    e.preventDefault()
  })
})
</script>

<style scoped>
.recognize-container {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.recognize-container h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.recognize-form {
  background: #fff;
  padding: 2rem;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #2196F3;
  background-color: #f9f9f9;
}

.upload-area.has-image {
  border-style: solid;
  border-color: #2196F3;
}

.upload-placeholder {
  color: #666;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.upload-hint {
  font-size: 0.9rem;
  color: #999;
  margin-top: 0.5rem;
}

.image-preview {
  position: relative;
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
}

.image-preview img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.change-image-btn {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
}

.recognize-btn {
  width: 100%;
  padding: 0.8rem;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.recognize-btn:hover:not(:disabled) {
  background: #1976D2;
}

.recognize-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.result-section {
  margin-top: 2rem;
  padding: 1.5rem;
  border-radius: 8px;
  text-align: center;
}

.result-section.success {
  background: #e8f5e9;
  border: 1px solid #4CAF50;
}

.result-section.error {
  background: #ffebee;
  border: 1px solid #f44336;
}

.result-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.result-section h3 {
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.result-section p {
  margin: 0.5rem 0;
  color: #555;
}

.user-id {
  font-size: 0.9rem;
  color: #888;
}

.error-message {
  margin-top: 1rem;
  padding: 0.8rem;
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 5px;
  text-align: center;
}

.tips-section {
  background: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
}

.tips-section h3 {
  margin-bottom: 1rem;
  color: #333;
}

.tips-section ul {
  margin: 0;
  padding-left: 1.5rem;
}

.tips-section li {
  margin-bottom: 0.5rem;
  color: #666;
}

@media (max-width: 768px) {
  .recognize-container {
    padding: 1rem;
  }
  
  .recognize-form {
    padding: 1.5rem;
  }
  
  .upload-area {
    padding: 1.5rem;
    min-height: 150px;
  }
}
</style>